﻿@{
    var isEmbed = Context?.Request?.Query["embed"].ToString() == "1";
    Layout = isEmbed ? null : "_Layout";
    ViewData["Title"] = "新增BOM";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

    <style>
    .bom-add-container {
            padding: 20px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    .page-title {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 30px;
        padding-bottom: 15px;
        border-bottom: 2px solid #1e88e5;
    }
    
    .form-section {
        margin-bottom: 30px;
            padding: 20px;
        border: 1px solid #e5e7eb;
            border-radius: 8px;
        background: #fafbfc;
    }
    
    .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
            margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .form-row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 20px;
    }
    
    .form-group {
        flex: 1;
        min-width: 250px;
    }
    
    .form-label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #333;
    }
    
    .required::after {
        content: " *";
        color: #dc3545;
    }
    
    .form-input {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
    }
    
    .form-input:focus {
        outline: none;
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
    }
    
    .form-select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
            background: white;
        cursor: pointer;
    }
    
    .form-textarea {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        min-height: 80px;
        resize: vertical;
    }
    
    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 8px;
    }
    
    .checkbox-input {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }
    
    .checkbox-label {
        font-size: 14px;
        color: #666;
        cursor: pointer;
    }
    
    .item-selector {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .item-input {
        flex: 1;
    }
    
    .selector-btn {
        padding: 10px 15px;
        background: #1e88e5;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        white-space: nowrap;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
    }
    
    .selector-btn:hover {
        background: #1565c0;
    }
    
    .section-actions {
        display: flex;
        gap: 10px;
            margin-bottom: 20px;
        }
    
    .btn-add {
        background: #1e88e5;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    
    .btn-add:hover {
        background: #1565c0;
    }
    
    .btn-remove {
        background: #ff6b35;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    
    .btn-remove:hover {
        background: #e55a2b;
    }
    
    .data-table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        overflow: hidden;
    }
    
    .data-table th,
    .data-table td {
        padding: 12px 8px;
        text-align: left;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .data-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }
    
    .data-table tr:nth-child(even) {
        background: #f9fafb;
    }
    
    .data-table tr:hover {
        background: #f0f4ff;
    }
    
    .no-data {
        text-align: center;
        padding: 40px;
        color: #666;
        font-size: 16px;
        background: #f9fafb;
    }
    
    .form-actions {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #e5e7eb;
    }
    
    .btn-close {
        background: #6c757d;
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        font-weight: 500;
    }
    
    .btn-close:hover {
        background: #5a6268;
    }
    
    .btn-confirm {
        background: #1e88e5;
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        font-weight: 500;
    }
    
    .btn-confirm:hover {
        background: #1565c0;
    }
    
    .quantity-input {
        width: 80px;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 3px;
        text-align: center;
        font-size: 14px;
    }
    
    .quantity-input:focus {
        outline: none;
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
    }
    
    .order-input {
        width: 60px;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 3px;
        text-align: center;
        font-size: 14px;
    }
    
    .order-input:focus {
        outline: none;
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
    }
    
    .workload-input {
        width: 100px;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 3px;
        text-align: center;
        font-size: 14px;
    }
    
    .workload-input:focus {
        outline: none;
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
    }
    
         /* 弹窗样式 */
     .modal-overlay {
         position: fixed;
         top: 0;
         left: 0;
         width: 100%;
         height: 100%;
         background: rgba(0, 0, 0, 0.5);
         z-index: 1000;
         display: none;
     }
     
     /* 确认弹窗样式 */
     .confirm-modal {
         position: fixed;
         top: 50%;
         left: 50%;
         transform: translate(-50%, -50%);
            background: white;
            border-radius: 8px;
         box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
         z-index: 1002;
         width: 400px;
         max-width: 90vw;
         display: none;
     }
    
    .modal-dialog {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        z-index: 1001;
        width: 800px;
        max-width: 90vw;
        max-height: 80vh;
        overflow: hidden;
    }
    
    .modal-header {
        background: #1e88e5;
        color: white;
        padding: 15px 20px;
        border-radius: 8px 8px 0 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .modal-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
    }
    
    .modal-close {
        background: none;
        border: none;
        color: white;
        font-size: 20px;
        cursor: pointer;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: background-color 0.3s;
    }
    
    .modal-close:hover {
        background: rgba(255, 255, 255, 0.2);
    }
    
    .modal-body {
        padding: 20px;
        max-height: 60vh;
        overflow-y: auto;
    }
    
    .search-panel {
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 6px;
        border: 1px solid #e9ecef;
    }
    
        .search-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
    
        .search-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
    
        .search-item label {
            min-width: 80px;
            font-weight: 500;
        color: #333;
        font-size: 14px;
    }
    
    .search-item input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        width: 150px;
    }
    
    .search-item input:focus {
        outline: none;
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
    }
    
    .search-buttons {
            display: flex;
            gap: 10px;
        }
    
    .btn-search {
            background: #1e88e5;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    
    .btn-search:hover {
        background: #1565c0;
    }
    
    .btn-reset {
        background: #6c757d;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    
    .btn-reset:hover {
        background: #5a6268;
    }
    
    .material-table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid #e5e7eb;
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 20px;
    }
    
    .material-table th,
    .material-table td {
        padding: 12px 8px;
        text-align: left;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .material-table th {
        background: #f8f9fa;
            font-weight: 600;
            color: #333;
        font-size: 14px;
    }
    
    .material-table tr:nth-child(even) {
        background: #f9fafb;
    }
    
    .material-table tr:hover {
        background: #f0f4ff;
        cursor: pointer;
    }
    
    .material-table tr.selected {
        background: #e3f2fd;
        border-left: 3px solid #1e88e5;
    }
    
    .modal-footer {
        padding: 15px 20px;
        border-top: 1px solid #e5e7eb;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
            background: #f8f9fa;
    }
    
    .btn-select {
        background: #28a745;
        color: white;
        border: none;
        padding: 10px 20px;
            border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
    }
    
    .btn-select:hover {
        background: #218838;
    }
    
    .btn-cancel {
        background: #6c757d;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
            font-weight: 500;
    }
    
    .btn-cancel:hover {
        background: #5a6268;
    }
    
    .pagination-info {
        text-align: center;
            color: #666;
        font-size: 14px;
        margin-bottom: 15px;
    }
    
    .pagination-controls {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 10px;
    }
    
    .page-btn {
        padding: 6px 12px;
        border: 1px solid #ddd;
        background: white;
            color: #333;
        cursor: pointer;
        border-radius: 3px;
        font-size: 14px;
    }
    
    .page-btn:hover {
        background: #f8f9fa;
    }
    
    .page-btn.active {
        background: #1e88e5;
        color: white;
        border-color: #1e88e5;
    }
    
    .page-btn:disabled {
        background: #f8f9fa;
        color: #ccc;
        cursor: not-allowed;
        }
    </style>

<div class="bom-add-container">
    <h1 class="page-title">新增BOM</h1>
    
    <!-- 基础信息部分 -->
    <div class="form-section">
        <h2 class="section-title">基础信息</h2>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label required">BOM编号</label>
                <input type="text" class="form-input" id="bomCode" value="BOM0000300160" readonly>
                <div class="checkbox-group">
                    <input type="checkbox" class="checkbox-input" id="systemCode" checked onchange="toggleSystemCode()">
                    <label class="checkbox-label" for="systemCode">系统编号</label>
                    <button type="button" class="btn-regenerate" onclick="regenerateBOMCode()" style="margin-left: 10px; padding: 5px 10px; background: #28a745; color: white; border: none; border-radius: 3px; cursor: pointer;">
                        <i class="fas fa-sync-alt"></i> 重新生成
                    </button>
                </div>
                </div>
            
            <div class="form-group">
                <label class="form-label">默认BOM</label>
                <div class="checkbox-group">
                    <input type="checkbox" class="checkbox-input" id="isDefault">
                    <label class="checkbox-label" for="isDefault">设为默认BOM</label>
                </div>
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">日产量</label>
                <input type="number" class="form-input" id="dailyOutput" placeholder="请输入日产量">
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">备注</label>
                <textarea class="form-textarea" id="remarks" placeholder="请输入备注"></textarea>
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label required">BOM主题</label>
                <input type="text" class="form-input" id="bomSubject" placeholder="请输入BOM主题">
            </div>
            
            <div class="form-group">
                <label class="form-label required">版本</label>
                <input type="text" class="form-input" id="version" placeholder="请输入版本">
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label required">成品名称</label>
                <div class="item-selector">
                    <input type="text" class="form-input item-input" id="productName" placeholder="请选择物品" readonly style="width: 60%;">
                    <button type="button" class="selector-btn" onclick="selectProduct()" style="width: 35%;">
                        <i class="fas fa-search"></i> 选择成品
                    </button>
                </div>
                </div>
            </div>
        </div>

    <!-- BOM配件部分 -->
    <div class="form-section">
        <h2 class="section-title">BOM配件</h2>
        
                 <div class="section-actions">
             <button type="button" class="btn-add" onclick="addComponent()">
                 <i class="fas fa-plus"></i> 添加
                </button>
             <button type="button" class="btn-remove" onclick="removeComponent()">
                 <i class="fas fa-minus"></i> 移除
                </button>
         </div>
        
                 <table class="layui-table" id="componentsTable" lay-filter="componentsTable">
         </table>
         

    </div>
    
    <!-- 工艺流程部分 -->
    <div class="form-section">
        <h2 class="section-title">工艺流程</h2>
        
        <div class="section-actions">
            <button type="button" class="btn-add" onclick="addProcess()">
                <i class="fas fa-plus"></i> 添加
                </button>
            <button type="button" class="btn-remove" onclick="removeProcess()">
                <i class="fas fa-minus"></i> 移除
                </button>
            </div>
        
        <table class="layui-table" id="processesTable" lay-filter="processesTable">
        </table>
        </div>

    <!-- 表单操作按钮 -->
    <div class="form-actions">
        <button type="button" class="btn-close" onclick="closeBOM()">
            <i class="fas fa-times"></i> 取消
        </button>
        <button type="button" class="btn-confirm" onclick="saveBOM()">
            <i class="fas fa-save"></i> 保存
        </button>
    </div>
                </div>

<!-- 工艺流程选择弹窗 -->
<div class="modal-overlay" id="processModal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3 class="modal-title">选择工艺流程</h3>
            <button class="modal-close" onclick="closeProcessModal()">
                <i class="fas fa-times"></i>
            </button>
                    </div>
                    
        <div class="modal-body">
        <!-- 搜索面板 -->
        <div class="search-panel">
            <div class="search-row">
                <div class="search-item">
                        <label>工艺编码:</label>
                        <input type="text" id="searchProcessCode" placeholder="请输入工艺编码">
                </div>
                <div class="search-item">
                        <label>工艺名称:</label>
                        <input type="text" id="searchProcessName" placeholder="请输入工艺名称">
                </div>
                    <div class="search-buttons">
                        <button class="btn-search" onclick="searchProcesses()">
                        <i class="fas fa-search"></i> 搜索
                    </button>
                        <button class="btn-reset" onclick="resetProcessSearch()">
                        <i class="fas fa-redo"></i> 重置
                    </button>
                </div>
            </div>
        </div>

            <!-- 工艺流程表格 -->
            <table class="layui-table" id="processesSelectTable" lay-filter="processesSelectTable">
            </table>
                    </div>

        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeProcessModal()">取消</button>
            <button class="btn-select" onclick="selectProcesses()">选择</button>
                    </div>
                </div>
            </div>

<!-- 成品选择弹窗 -->
<div class="modal-overlay" id="productModal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3 class="modal-title">选择成品</h3>
            <button class="modal-close" onclick="closeProductModal()">
                <i class="fas fa-times"></i>
                </button>
        </div>
        
        <div class="modal-body">
            <!-- 搜索面板 -->
            <div class="search-panel">
                <div class="search-row">
                    <div class="search-item">
                        <label>成品编号/名称:</label>
                        <input type="text" id="searchProductNameAndCode" placeholder="请输入成品编号或名称">
                    </div>
                    <div class="search-item">
                        <label>成品类型:</label>
                        <select id="searchProductType">
                            <option value="">全部类型</option>
                            <option value="1">建筑制成品</option>
                            <option value="2">工业制成品</option>
                        </select>
                    </div>
                    <div class="search-buttons">
                        <button class="btn-search" onclick="searchProducts()">
                            <i class="fas fa-search"></i> 搜索
                </button>
                        <button class="btn-reset" onclick="resetProductSearch()">
                            <i class="fas fa-redo"></i> 重置
                </button>
                    </div>
            </div>
        </div>

            <!-- 成品表格 -->
            <table class="layui-table" id="productsSelectTable" lay-filter="productsSelectTable">
            </table>
            
            <!-- 操作列模板 -->
            <script type="text/html" id="productOperationBar">
                <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="selectProduct">
                    <i class="layui-icon layui-icon-ok"></i> 选择成品
                </button>
            </script>
                    </div>
        
        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeProductModal()">取消</button>
        </div>
    </div>
                </div>

<!-- 材料选择弹窗 -->
<div class="modal-overlay" id="materialModal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3 class="modal-title">选择材料</h3>
            <button class="modal-close" onclick="closeMaterialModal()">
                <i class="fas fa-times"></i>
            </button>
                    </div>
                    
        <div class="modal-body">
            <!-- 搜索面板 -->
            <div class="search-panel">
                <div class="search-row">
                    <div class="search-item">
                        <label>材料编号:</label>
                        <input type="text" id="searchMaterialCode" placeholder="请输入材料编号">
                        </div>
                    <div class="search-item">
                        <label>材料名称:</label>
                        <input type="text" id="searchMaterialName" placeholder="请输入材料名称">
                        </div>
                    <div class="search-buttons">
                        <button class="btn-search" onclick="searchMaterials()">
                            <i class="fas fa-search"></i> 搜索
                        </button>
                        <button class="btn-reset" onclick="resetMaterialSearch()">
                            <i class="fas fa-redo"></i> 重置
                        </button>
                        </div>
                        </div>
                        </div>

                         <!-- 材料表格 -->
             <table class="layui-table" id="materialsSelectTable" lay-filter="materialsSelectTable">
             </table>
            
            
                    </div>

        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeMaterialModal()">取消</button>
            <button class="btn-select" onclick="selectMaterials()">选择</button>
            </div>
        </div>
    </div>

    <script>
    let componentCounter = 0;
    let processCounter = 0;
    let components = [];
    let processes = [];
    
         // 材料选择弹窗相关变量
     let materialCurrentPage = 1;
     let materialPageSize = 10;
     let materialTotalCount = 0;
     let materialTotalPages = 0;
     let materials = [];
     let selectedMaterials = [];
     
     // 工艺流程选择弹窗相关变量
     let processCurrentPage = 1;
     let processPageSize = 10;
     let processTotalCount = 0;
     let processTotalPages = 0;
     let processList = [];
     let selectedProcesses = [];
     
     // 成品选择弹窗相关变量
     let productCurrentPage = 1;
     let productPageSize = 10;
     let productTotalCount = 0;
     let productTotalPages = 0;
     let productList = [];
     let selectedProduct = null;
    
    // 页面加载完成后初始化
    $(document).ready(function() {
        console.log('新增BOM页面已加载');
        // 初始化系统编号状态
        toggleSystemCode();
        
                 // 初始化Layui表格
         layui.use(['table', 'layer'], function(){
             window.table = layui.table;
             window.layer = layui.layer;
             
             // 初始化BOM配件表格
             initComponentsTable();
             
             // 初始化工艺流程选择表格
             initProcessesSelectTable();
             
             // 初始化工艺流程表格
             initProcessesTable();
             
             // 初始化材料选择表格
             initMaterialsSelectTable();
             
             // 初始化成品选择表格
             initProductsSelectTable();
         });
    });
    
    // 生成BOM编号（BOM+时间戳+随机数）
    function generateBOMCode() {
        // 获取当前时间戳的后6位
        const timestamp = Date.now().toString().slice(-6);
        // 生成3位随机数
        const randomNumber = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        const bomCode = `BOM${timestamp}${randomNumber}`;
        document.getElementById('bomCode').value = bomCode;
        console.log('生成BOM编号:', bomCode);
    }
    
    // 切换系统编号功能
    function toggleSystemCode() {
        const systemCodeCheckbox = document.getElementById('systemCode');
        const bomCodeInput = document.getElementById('bomCode');
        
        console.log('系统编号复选框状态:', systemCodeCheckbox.checked);
        
        if (systemCodeCheckbox.checked) {
            // 选中时：自动生成编号，输入框只读
            bomCodeInput.readOnly = true;
            bomCodeInput.style.backgroundColor = '#f5f5f5';
            bomCodeInput.style.cursor = 'not-allowed';
            // 直接生成BOM编号，不进行唯一性检查
            generateBOMCode();
            console.log('已启用系统编号，自动生成BOM编号');
        } else {
            // 未选中时：支持手动输入，输入框可编辑
            bomCodeInput.readOnly = false;
            bomCodeInput.style.backgroundColor = 'white';
            bomCodeInput.style.cursor = 'text';
            bomCodeInput.focus(); // 聚焦到输入框
            console.log('已禁用系统编号，支持手动输入');
        }
    }
    
    // 选择成品
    function selectProduct() {
        console.log('选择成品');
        // 打开成品选择弹窗
        openProductModal();
    }
    
    // 添加配件
    function addComponent() {
        // 打开材料选择弹窗
        openMaterialModal();
    }
    
         // 移除配件
     function removeComponent() {
         if (!window.table) return;
         
         if (components.length === 0) {
             if (window.layer) {
                 window.layer.msg('当前没有配件可移除', {icon: 2});
             } else {
                 alert('当前没有配件可移除');
             }
             return;
         }
         
         // 获取选中的行数据
         const checkStatus = window.table.checkStatus('componentsTable');
         const selectedData = checkStatus.data;
         
         if (selectedData.length === 0) {
             if (window.layer) {
                 window.layer.msg('请选择要移除的配件', {icon: 2});
             } else {
                 alert('请选择要移除的配件');
             }
             return;
         }
         
         if (window.layer) {
             window.layer.confirm(`确定要移除选中的 ${selectedData.length} 个配件吗？`, {
                 icon: 3,
                 title: '确认移除'
             }, function(index) {
                 // 根据选中的行数据移除配件
                 selectedData.forEach(row => {
                     components = components.filter(item => item.id !== row.id);
                 });
                 
                 // 重新渲染表格
                 renderComponentsTable();
                 
                 window.layer.close(index);
                 window.layer.msg(`成功移除 ${selectedData.length} 个配件`, {icon: 1});
             });
         } else {
             if (confirm(`确定要移除选中的 ${selectedData.length} 个配件吗？`)) {
                 // 根据选中的行数据移除配件
                 selectedData.forEach(row => {
                     components = components.filter(item => item.id !== row.id);
                 });
                 
                 // 重新渲染表格
                 renderComponentsTable();
                 
                 alert(`成功移除 ${selectedData.length} 个配件`);
             }
         }
     }
    
         // 初始化BOM配件表格
     function initComponentsTable() {
         if (!window.table) return;
         
         window.table.render({
             elem: '#componentsTable',
             data: [],
             page: false,
             height: 'auto',
                cols: [[
                 {type: 'checkbox', fixed: 'left'},
                 {type: 'numbers', title: '序号', width: '15%', align: 'center'},
                 {field: 'itemCode', title: '编号', width: '25%'},
                 {field: 'itemName', title: '名称', width: '35%'},
                 {field: 'materialType', title: '类型', width: '25%', align: 'center'}
             ]],
             done: function() {
                 // 表格渲染完成后的回调
                 console.log('BOM配件表格初始化完成');
             }
         });
         

     }
    
    // 渲染配件表格
    function renderComponentsTable() {
        if (!window.table) return;
        
        // 准备表格数据
        const tableData = components.map((component, index) => ({
            id: component.id,
            index: index + 1,
            itemCode: component.itemCode || '',
            itemName: component.itemName || '',
            materialType: getMaterialTypeName(component.materialType) || '未知',
            materialId: component.materialId,
            spec: component.spec || '',
            unit: component.unit || '',
            brand: component.brand || '',
            quantity: component.quantity || 1,
            lossRate: component.lossRate || 0
        }));
        
        // 重新加载表格数据
        window.table.reload('componentsTable', {
            data: tableData
        });
    }
    
    // 更新配件信息
    function updateComponent(id, field, value) {
        const component = components.find(item => item.id === id);
        if (component) {
            component[field] = value;
        }
    }
    
    
    
    
     

    
         // 添加工序
     function addProcess() {
         // 打开工艺流程选择弹窗
         openProcessModal();
     }
     
     // 初始化工艺流程表格
     function initProcessesTable() {
         if (!window.table) return;
         
         window.table.render({
             elem: '#processesTable',
             data: [],
             page: false,
             height: 'auto',
             cols: [[
                 {type: 'checkbox', fixed: 'left'},
                 {type: 'numbers', title: '序号', width: '10%', align: 'center'},
                 {field: 'processCode', title: '工序编码', width: '20%'},
                 {field: 'processName', title: '工序名称', width: '25%'},
                 {field: 'processingOrder', title: '加工顺序', width: '15%', align: 'center'},
                 {field: 'responsiblePerson', title: '负责人', width: '15%'},
                 {field: 'department', title: '部门', width: '15%', templet: function(d){
                     return getDepartmentName(d.department);
                 }}
             ]],
             done: function() {
                 console.log('工艺流程表格初始化完成');
             }
         });
     }
     
     // 获取部门名称
     function getDepartmentName(departmentId) {
         switch (parseInt(departmentId)) {
             case 1: return '生产部';
             case 2: return '质检部';
             case 3: return '技术部';
             default: return '未知部门';
         }
     }
    
         // 移除工序
     function removeProcess() {
         if (!window.table) return;
         
         if (processes.length === 0) {
             if (window.layer) {
                 window.layer.msg('当前没有工序可移除', {icon: 2});
             } else {
                 alert('当前没有工序可移除');
             }
             return;
         }
         
         // 获取选中的行数据
         const checkStatus = window.table.checkStatus('processesTable');
         const selectedData = checkStatus.data;
         
         if (selectedData.length === 0) {
             if (window.layer) {
                 window.layer.msg('请选择要移除的工序', {icon: 2});
             } else {
                 alert('请选择要移除的工序');
             }
             return;
         }
         
         if (window.layer) {
             window.layer.confirm(`确定要移除选中的 ${selectedData.length} 个工序吗？`, {
                 icon: 3,
                 title: '确认移除'
             }, function(index) {
                 // 根据选中的行数据移除工序
                 selectedData.forEach(row => {
                     processes = processes.filter(item => item.id !== row.id);
                 });
                 
                 // 重新渲染表格
                 renderProcessesTable();
                 
                 window.layer.close(index);
                 window.layer.msg(`成功移除 ${selectedData.length} 个工序`, {icon: 1});
             });
         } else {
             if (confirm(`确定要移除选中的 ${selectedData.length} 个工序吗？`)) {
                 // 根据选中的行数据移除工序
                 selectedData.forEach(row => {
                     processes = processes.filter(item => item.id !== row.id);
                 });
                 
                 // 重新渲染表格
                 renderProcessesTable();
                 
                 alert(`成功移除 ${selectedData.length} 个工序`);
             }
         }
     }
    
         // 渲染工序表格
     function renderProcessesTable() {
         if (!window.table) return;
         
         // 准备表格数据
         const tableData = processes.map((process, index) => ({
             id: process.id,
             index: index + 1,
             processCode: process.processCode || '',
             processName: process.processName || '',
             processingOrder: process.processingOrder || 1,
             responsiblePerson: process.responsiblePerson || '',
             department: process.department || ''
         }));
         
         // 重新加载表格数据
         window.table.reload('processesTable', {
             data: tableData
         });
     }
    
    // 更新工序信息
    function updateProcess(id, field, value) {
        const process = processes.find(item => item.id === id);
        if (process) {
            process[field] = value;
        }
    }
    
    
    
    // 确认BOM
    function confirmBOM() {
        // 收集表单数据
        const bomData = {
            bomCode: document.getElementById('bomCode').value,
            isDefault: document.getElementById('isDefault').checked,
            productType: document.getElementById('productType').value,
            dailyOutput: document.getElementById('dailyOutput').value,
            remarks: document.getElementById('remarks').value,
            bomSubject: document.getElementById('bomSubject').value,
            version: document.getElementById('version').value,
            productName: document.getElementById('productName').value,
            components: components,
            processes: processes
        };
        
        console.log('确认BOM数据:', bomData);
        
        // 这里可以实现实际的保存逻辑
        if (window.layer) {
            window.layer.msg('BOM保存成功！', {icon: 1});
        } else {
            alert('BOM保存成功！');
        }
        
        // 保存成功后返回列表页
        if (window.parent && window.parent.loadContent) {
            // 如果在iframe中，通知父页面返回列表
            window.parent.postMessage({ action: 'returnToList' }, '*');
        }
    }
    

    
    // 关闭BOM
    function closeBOM() {
        if (window.layer) {
            window.layer.confirm('确定要关闭吗？未保存的数据将丢失。', {
                icon: 3,
                title: '确认关闭'
            }, function(index) {
                // 返回列表页
                if (window.parent && window.parent.loadContent) {
                    // 如果在iframe中，通知父页面返回列表
                    window.parent.postMessage({ action: 'returnToList' }, '*');
                }
                window.layer.close(index);
            });
        } else {
            if (confirm('确定要关闭吗？未保存的数据将丢失。')) {
                // 返回列表页
                if (window.parent && window.parent.loadContent) {
                    // 如果在iframe中，通知父页面返回列表
                    window.parent.postMessage({ action: 'returnToList' }, '*');
                }
            }
        }
    }
    
    // 监听来自父页面的消息
    window.addEventListener('message', function(event) {
        if (event.data.action === 'returnToList') {
            // 处理返回列表的逻辑
            console.log('收到返回列表指令');
        }
    });
    
         // ==================== 工艺流程选择弹窗功能 ====================
     
     // 初始化工艺流程选择表格
     function initProcessesSelectTable() {
         if (!window.table) return;
         
         window.table.render({
             elem: '#processesSelectTable',
             data: [],
             page: true,
             limit: processPageSize,
             limits: [10, 20, 50],
             cols: [[
                 {type: 'checkbox', fixed: 'left'},
                 {field: 'craftsCode', title: '工艺编码', width: '20%'},
                 {field: 'craftsName', title: '工艺名称', width: '30%'},
                 {field: 'responsibilityName', title: '负责人', width: '15%'},
                 {field: 'note', title: '备注', width: '25%'},
                 {field: 'createTime', title: '创建时间', width: '20%', templet: function(d){
                     return d.createTime ? new Date(d.createTime).toLocaleDateString() : '';
                 }}
             ]],
             done: function() {
                 console.log('工艺流程选择表格初始化完成');
             }
         });
     }
     
     // 打开工艺流程选择弹窗
     function openProcessModal() {
         // 清空之前的选择
         selectedProcesses = [];
         
         // 显示弹窗
         document.getElementById('processModal').style.display = 'block';
         
         // 重置搜索条件
         resetProcessSearch();
         
         // 加载工艺流程数据
         loadProcesses();
         
         console.log('工艺流程选择弹窗已打开');
     }
     
     // 关闭工艺流程选择弹窗
     function closeProcessModal() {
         document.getElementById('processModal').style.display = 'none';
         // 清空选择
         selectedProcesses = [];
     }
     
     // 加载工艺流程数据
     function loadProcesses() {
         const processCode = document.getElementById('searchProcessCode').value.trim();
         const processName = document.getElementById('searchProcessName').value.trim();
         
         console.log('开始加载工艺流程数据...');
         
         // 构建查询参数
         const params = new URLSearchParams({
             PageIndex: processCurrentPage,
             PageSize: processPageSize
         });
         
         if (processCode) {
             params.append('CraftsCode', processCode);
         }
         
         if (processName) {
             params.append('CraftsName', processName);
         }
         
         console.log('查询参数:', params.toString());
         
         // 调用API
         $.ajax({
             url: `http://localhost:5161/api/Process/CraftsQuery?${params.toString()}`,
             type: 'GET',
             dataType: 'json',
             success: function(response) {
                 console.log('API响应:', response);
                 
                 if (response.code === 200) {
                     processList = response.data.list || [];
                     processTotalCount = response.data.totalCount || 0;
                     processTotalPages = response.data.totalPages || 0;
                     
                     console.log('工艺流程数据:', processList);
                     console.log('总数:', processTotalCount);
                     
                     // 重新加载表格数据
                     window.table.reload('processesSelectTable', {
                         data: processList,
                         page: {
                             curr: processCurrentPage,
                             count: processTotalCount,
                             limit: processPageSize
                         }
                     });
                 } else {
                     console.error('API返回错误:', response.message);
                     if (window.layer) {
                         window.layer.msg('加载工艺流程数据失败：' + response.message, {icon: 2});
                     } else {
                         alert('加载工艺流程数据失败：' + response.message);
                     }
                 }
             },
             error: function(xhr, status, error) {
                 console.error('API调用失败:', error);
                 console.error('状态:', status);
                 console.error('响应:', xhr.responseText);
                 
                 // 如果API调用失败，使用模拟数据
                 console.log('使用模拟数据');
                 processList = [
                     { id: 1, craftsCode: 'CRA3532', craftsName: '苹果糖生产工艺', responsibilityName: '张伟', note: '好吃', createTime: '2025-08-28T21:06:16.583666' },
                     { id: 2, craftsCode: 'CRA3533', craftsName: '巧克力制作工艺', responsibilityName: '李强', note: '甜而不腻', createTime: '2025-08-28T21:06:16.583666' },
                     { id: 3, craftsCode: 'CRA3534', craftsName: '糖果包装工艺', responsibilityName: '王芳', note: '精美包装', createTime: '2025-08-28T21:06:16.583666' }
                 ];
                 processTotalCount = 3;
                 processTotalPages = 1;
                 
                 // 重新加载表格数据
                 window.table.reload('processesSelectTable', {
                     data: processList,
                     page: {
                         curr: processCurrentPage,
                         count: processTotalCount,
                         limit: processPageSize
                     }
                 });
             }
         });
     }
     
     // 搜索工艺流程
     function searchProcesses() {
         processCurrentPage = 1;
         loadProcesses();
     }
     
     // 重置工艺流程搜索
     function resetProcessSearch() {
         document.getElementById('searchProcessCode').value = '';
         document.getElementById('searchProcessName').value = '';
         processCurrentPage = 1;
     }
     
     // 选择工艺流程
     function selectProcesses() {
         console.log('开始选择工艺流程...');
         
         // 获取选中的行数据
         const checkStatus = window.table.checkStatus('processesSelectTable');
         const selectedData = checkStatus.data;
         
         console.log('选中的工艺流程:', selectedData);
         
         if (selectedData.length === 0) {
             console.log('没有选中的工艺流程');
             if (window.layer) {
                 window.layer.msg('请选择要添加的工艺流程', {icon: 2});
             } else {
                 alert('请选择要添加的工艺流程');
             }
             return;
         }
         
         // 将选中的工艺流程添加到工序列表
         selectedData.forEach(process => {
             processCounter++;
             const newProcess = {
                 id: process.id, // 保存真实的工艺流程ID
                 processCode: process.craftsCode || '',
                 processName: process.craftsName || '',
                 processingOrder: 1,
                 processFlow: process.craftsName || '',
                 responsiblePerson: process.responsibilityName || '',
                 department: 1, // 默认设置为生产部
                 unitWorkload: '',
                 remarks: process.note || ''
             };
             
             processes.push(newProcess);
             console.log('=== 添加工序详情 ===');
             console.log('原始工艺数据:', process);
             console.log('提取的真实ID:', process.id);
             console.log('构建的新工序对象:', newProcess);
         });
         
         console.log('当前工序列表:', processes);
         
         // 重新渲染工序表格
         renderProcessesTable();
         
         // 关闭弹窗
         closeProcessModal();
         
         // 显示成功消息
         if (window.layer) {
             window.layer.msg(`成功添加 ${selectedData.length} 个工艺流程到工序列表`, {icon: 1});
         } else {
             alert(`成功添加 ${selectedData.length} 个工艺流程到工序列表`);
         }
     }
     
     // ==================== 材料选择弹窗功能 ====================
    
         // 初始化材料选择表格
     function initMaterialsSelectTable() {
         if (!window.table) return;
         
         window.table.render({
             elem: '#materialsSelectTable',
             data: [],
             page: true,
             limit: materialPageSize,
             limits: [10, 20, 50],
             cols: [[
                 {type: 'checkbox', fixed: 'left'},
                 {field: 'materialCode', title: '材料编号', width: '30%'},
                 {field: 'materialName', title: '材料名称', width: '40%'},
                 {field: 'materialType', title: '材料类型', width: '30%', templet: function(d){
                     return getMaterialTypeName(d.materialType);
                 }}
             ]],
             done: function() {
                 console.log('材料选择表格初始化完成');
             }
         });
     }
     
     // 打开材料选择弹窗
     function openMaterialModal() {
         // 清空之前的选择
         selectedMaterials = [];
         
         // 显示弹窗
         document.getElementById('materialModal').style.display = 'block';
         
         // 重置搜索条件
         resetMaterialSearch();
         
         // 加载材料数据
         loadMaterials();
         
         console.log('材料选择弹窗已打开');
     }
    
         // 关闭材料选择弹窗
     function closeMaterialModal() {
         document.getElementById('materialModal').style.display = 'none';
         // 清空选择
         selectedMaterials = [];
     }
    
         // 加载材料数据
     function loadMaterials() {
         const materialCode = document.getElementById('searchMaterialCode').value.trim();
         const materialName = document.getElementById('searchMaterialName').value.trim();
         
         console.log('开始加载材料数据...');
         
         // 构建查询参数
         const params = new URLSearchParams({
             PageIndex: materialCurrentPage,
             PageSize: materialPageSize
         });
         
         if (materialCode) {
             params.append('MaterialCode', materialCode);
         }
         
         if (materialName) {
             params.append('MaterialName', materialName);
         }
         
         console.log('查询参数:', params.toString());
         
         // 调用API
         $.ajax({
             url: `http://localhost:5287/api/BomManage/MaterailQuery?${params.toString()}`,
             type: 'GET',
             dataType: 'json',
             success: function(response) {
                 console.log('API响应:', response);
                 
                 if (response.code === 200) {
                     materials = response.data.list || [];
                     materialTotalCount = response.data.totalCount || 0;
                     materialTotalPages = response.data.totalPages || 0;
                     
                     console.log('材料数据:', materials);
                     console.log('总数:', materialTotalCount);
                     
                     // 重新加载表格数据
                     window.table.reload('materialsSelectTable', {
                         data: materials,
                         page: {
                             curr: materialCurrentPage,
                             count: materialTotalCount,
                             limit: materialPageSize
                         }
                     });
                 } else {
                     console.error('API返回错误:', response.message);
                     if (window.layer) {
                         window.layer.msg('加载材料数据失败：' + response.message, {icon: 2});
                     } else {
                         alert('加载材料数据失败：' + response.message);
                     }
                 }
             },
             error: function(xhr, status, error) {
                 console.error('API调用失败:', error);
                 console.error('状态:', status);
                 console.error('响应:', xhr.responseText);
                 
                                                     // 如果API调用失败，使用模拟数据
                 
                  materialTotalCount = 3;
                  materialTotalPages = 1;
                 
                  // 重新加载表格数据
                  window.table.reload('materialsSelectTable', {
                      data: materials,
                      page: {
                          curr: materialCurrentPage,
                          count: materialTotalCount,
                          limit: materialPageSize
                      }
                  });
             }
         });
     }
    
    
    
    // 获取材料类型名称
    function getMaterialTypeName(type) {
        switch (type) {
            case 1: return '原材料';
            case 2: return '半成品';
            case 3: return '成品';
            default: return '未知';
        }
    }
    
         
    
    // 搜索材料
    function searchMaterials() {
        materialCurrentPage = 1;
        loadMaterials();
    }
    
    // 重置材料搜索
    function resetMaterialSearch() {
        document.getElementById('searchMaterialCode').value = '';
        document.getElementById('searchMaterialName').value = '';
        materialCurrentPage = 1;
    }
    
    
    
         // 选择材料
     function selectMaterials() {
         console.log('开始选择材料...');
         
         // 获取选中的行数据
         const checkStatus = window.table.checkStatus('materialsSelectTable');
         const selectedData = checkStatus.data;
         
         console.log('选中的材料:', selectedData);
         
         if (selectedData.length === 0) {
             console.log('没有选中的材料');
             if (window.layer) {
                 window.layer.msg('请选择要添加的材料', {icon: 2});
             } else {
                 alert('请选择要添加的材料');
             }
             return;
         }
         
                  // 将选中的材料添加到配件列表
         selectedData.forEach(material => {
             componentCounter++;
             const component = {
                 id: componentCounter,
                 itemCode: material.materialCode || '',
                 itemName: material.materialName || '',
                 spec: '', // 规格型号需要用户填写
                 unit: '', // 单位需要用户填写
                 brand: '', // 品牌需要用户填写
                 quantity: 1,
                 lossRate: 0,
                 materialId: material.id, // 保存材料ID用于后续操作
                 materialType: material.materialType
             };
             
             components.push(component);
             console.log('添加配件:', component);
         });
         
         console.log('当前配件列表:', components);
         
         // 重新渲染配件表格
         renderComponentsTable();
         
         // 关闭弹窗
         closeMaterialModal();
         
                  // 显示成功消息
         if (window.layer) {
             window.layer.msg(`成功添加 ${selectedData.length} 个材料到配件列表`, {icon: 1});
         } else {
             alert(`成功添加 ${selectedData.length} 个材料到配件列表`);
         }
     }
     
     // ==================== 成品选择相关函数 ====================
     
     // 初始化成品选择表格
     function initProductsSelectTable() {
         if (!window.table) return;
         window.table.render({
             elem: '#productsSelectTable',
             data: [],
             page: true,
             limit: productPageSize,
             limits: [10, 20, 50],
                cols: [[
                 {type: 'numbers', title: '序号', width: '8%', align: 'center'},
                 {field: 'goodsName', title: '成品名称', width: '25%'},
                 {field: 'goodsCode', title: '成品编号', width: '15%'},
                 {field: 'goodsType', title: '成品类型', width: '15%', templet: function(d){
                     return getProductTypeName(d.goodsType);
                 }},
                 {field: 'goodsStatus', title: '成品状态', width: '12%', templet: function(d){
                     return d.goodsStatus ? '可生产' : '停止生产';
                 }},
                 {field: 'oneprice', title: '单件成本', width: '10%', align: 'right', templet: function(d){
                     return '¥' + (d.oneprice || 0);
                 }},
                 {field: 'operation', title: '操作', width: '15%', align: 'center', toolbar: '#productOperationBar'}
             ]],
             done: function() {
                 console.log('成品选择表格初始化完成');
             }
         });
         
         // 监听工具条事件
         window.table.on('tool(productsSelectTable)', function(obj){
             const data = obj.data;
             if(obj.event === 'selectProduct'){
                 selectProductFromTable(data);
             }
         });
     }
     
     // 打开成品选择弹窗
     function openProductModal() {
         console.log('打开成品选择弹窗');
         document.getElementById('productModal').style.display = 'flex';
         
         // 重置搜索条件
         document.getElementById('searchProductNameAndCode').value = '';
         document.getElementById('searchProductType').value = '';
         
         // 加载成品数据
         loadProducts();
     }
     
     // 关闭成品选择弹窗
     function closeProductModal() {
         console.log('关闭成品选择弹窗');
         document.getElementById('productModal').style.display = 'none';
         // 注意：不要在这里重置selectedProduct，因为可能已经选择了成品
     }
     
     // 重置成品选择（仅在需要时调用）
     function resetProductSelection() {
         console.log('重置成品选择');
         selectedProduct = null;
         document.getElementById('productName').value = '';
     }
     
     // 加载成品数据
     function loadProducts() {
         console.log('加载成品数据，页码:', productCurrentPage);
         
         const nameAndCode = document.getElementById('searchProductNameAndCode').value.trim();
         const goodsType = document.getElementById('searchProductType').value;
         
         // 构建请求参数
         const params = {
             PageIndex: productCurrentPage,
             PageSize: productPageSize
         };
         
         if (nameAndCode) {
             params.NameAndCode = nameAndCode;
         }
         
         if (goodsType) {
             params.GoodsType = parseInt(goodsType);
         }
         
         console.log('请求参数:', params);
         
         // 发送AJAX请求
         $.ajax({
             url: 'http://localhost:5287/api/BomManage/GoodsQuery',
             type: 'GET',
             data: params,
             dataType: 'json',
             success: function(response) {
                 console.log('成品数据加载成功:', response);
                 
                 if (response && response.code === 200 && response.data) {
                     productList = response.data.list || [];
                     productTotalCount = response.data.totalCount || 0;
                     productTotalPages = response.data.totalPages || 0;
                     
                     console.log('成品列表:', productList);
                     console.log('总数:', productTotalCount, '总页数:', productTotalPages);
                     
                     // 重新加载表格数据
                     window.table.reload('productsSelectTable', {
                         data: productList,
                         page: {
                             curr: productCurrentPage,
                             count: productTotalCount,
                             limit: productPageSize
                         }
                     });
                 } else {
                     console.error('API返回数据格式错误:', response);
                     if (window.layer) {
                         window.layer.msg('数据加载失败', {icon: 2});
                     }
                 }
             },
             error: function(xhr, status, error) {
                 console.error('加载成品数据失败:', error);
                 console.error('状态:', status);
                 console.error('响应:', xhr.responseText);
                 
                 // 如果API调用失败，使用模拟数据
                 productList = [
                     {
                         id: 1,
                         goodsCode: 'GOD00001',
                         goodsName: '运输车罐装水泥',
                         goodsType: 1,
                         goodsStatus: true,
                         oneprice: 600
                     },
                     {
                         id: 2,
                         goodsCode: 'GOD00002',
                         goodsName: '工业用钢材',
                         goodsType: 2,
                         goodsStatus: true,
                         oneprice: 1200
                     },
                     {
                         id: 3,
                         goodsCode: 'GOD00003',
                         goodsName: '建筑用砖块',
                         goodsType: 1,
                         goodsStatus: false,
                         oneprice: 50
                     }
                 ];
                 
                 productTotalCount = 3;
                 productTotalPages = 1;
                 
                 // 重新加载表格数据
                 window.table.reload('productsSelectTable', {
                     data: productList,
                     page: {
                         curr: productCurrentPage,
                         count: productTotalCount,
                         limit: productPageSize
                     }
                 });
             }
         });
     }
     
     // 获取成品类型名称
     function getProductTypeName(type) {
         switch(type) {
             case 1: return '建筑制成品';
             case 2: return '工业制成品';
             default: return '未知类型';
         }
     }
     
     // 搜索成品
     function searchProducts() {
         console.log('搜索成品');
         productCurrentPage = 1;
         loadProducts();
     }
     
     // 重置成品搜索
     function resetProductSearch() {
         console.log('重置成品搜索');
         document.getElementById('searchProductNameAndCode').value = '';
         document.getElementById('searchProductType').value = '';
         productCurrentPage = 1;
         loadProducts();
     }
     
     // 从表格选择成品
     function selectProductFromTable(product) {
         console.log('从表格选择成品:', product);
         console.log('成品真实ID:', product.id);
         console.log('成品编号:', product.goodsCode);
         console.log('成品名称:', product.goodsName);
         
         // 将选中的成品设置到表单中
         document.getElementById('productName').value = product.goodsName;
         
         // 保存选中的成品信息（包含真实ID）
         selectedProduct = product;
         
         // 关闭弹窗
         closeProductModal();
         
         // 显示成功消息
         if (window.layer) {
             window.layer.msg(`已选择成品: ${product.goodsName} (ID: ${product.id})`, {icon: 1});
         } else {
             alert(`已选择成品: ${product.goodsName} (ID: ${product.id})`);
         }
     }
     
         // 确认选择成品（保留原有功能，但不再使用）
    function confirmSelectProduct() {
        if (window.layer) {
            window.layer.msg('请点击表格中的"选择"按钮来选择成品', {icon: 2});
        } else {
            alert('请点击表格中的"选择"按钮来选择成品');
        }
    }
    
    // ==================== BOM保存功能 ====================
    
    // 保存BOM
    function saveBOM() {
        console.log('开始保存BOM');
        console.log('当前selectedProduct状态:', selectedProduct);
        console.log('selectedProduct类型:', typeof selectedProduct);
        console.log('selectedProduct是否为null:', selectedProduct === null);
        console.log('selectedProduct是否为undefined:', selectedProduct === undefined);
        
        // 构建请求数据
        const bomData = buildBOMData();
        console.log('BOM数据:', bomData);
        
        // 显示加载提示
        if (window.layer) {
            window.layer.load(1, {shade: [0.1,'#fff']});
        }
        
        // 发送AJAX请求
        $.ajax({
            url: 'http://localhost:5287/api/BomManage/BomAdd',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(bomData),
            dataType: 'json',
            success: function(response) {
                console.log('BOM保存成功:', response);
                
                if (window.layer) {
                    window.layer.closeAll('loading');
                }
                
                if (response && response.code === 200) {
                    if (window.layer) {
                        window.layer.msg('BOM保存成功', {icon: 1}, function() {
                            // 保存成功后返回列表页面
                            if (window.parent && window.parent.postMessage) {
                                window.parent.postMessage({ 
                                    action: 'returnToList',
                                    url: '/Process/BOMList',
                                    title: 'BOM管理'
                                }, '*');
                            } else {
                                window.location.href = '/Process/BOMList';
                            }
                        });
                    } else {
                        alert('BOM保存成功');
                        window.location.href = '/Process/BOMList';
                    }
                } else {
                    if (window.layer) {
                        window.layer.msg(response.message || '保存失败', {icon: 2});
                    } else {
                        alert(response.message || '保存失败');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('BOM保存失败:', error);
                console.error('状态:', status);
                console.error('响应:', xhr.responseText);
                
                if (window.layer) {
                    window.layer.closeAll('loading');
                    window.layer.msg('保存失败: ' + error, {icon: 2});
                } else {
                    alert('保存失败: ' + error);
                }
            }
        });
    }
    
    // 构建BOM数据
    function buildBOMData() {
        // 获取基础信息
        const bomCode = document.getElementById('bomCode').value.trim();
        const bomTopic = document.getElementById('bomSubject').value.trim();
        const bomVersion = document.getElementById('version').value.trim();
        const isDefaultBom = document.getElementById('isDefault').checked;
        const dayPlannum = parseInt(document.getElementById('dailyOutput').value) || 0;
        const note = document.getElementById('remarks').value.trim();
        
        // 构建midlist（BOM配件主键ID字符串）
        const midlist = components.map(component => component.materialId || component.id).join(',');
        
        // 构建cidlist（工艺流程主键ID字符串）
        const cidlist = processes.map(process => process.id).join(',');
        
        // 获取成品ID
        const goodsId = selectedProduct ? selectedProduct.id : 0;
        
        console.log('=== BOM数据构建详情 ===');
        console.log('选中的成品对象:', selectedProduct);
        console.log('成品真实ID:', goodsId);
        console.log('配件列表:', components);
        console.log('配件ID列表 (midlist):', midlist);
        console.log('工艺流程列表:', processes);
        console.log('工艺流程ID列表 (cidlist):', cidlist);
        console.log('=== cidlist构建详情 ===');
        processes.forEach((process, index) => {
            console.log(`工艺流程${index + 1}:`, {
                '序号': index + 1,
                '真实ID': process.id,
                '工艺编码': process.processCode,
                '工艺名称': process.processName
            });
        });
        console.log('最终cidlist字符串:', cidlist);
        
        const bomData = {
            bomCode: bomCode,
            bomTopic: bomTopic,
            bomVersion: bomVersion,
            isDefaultBom: isDefaultBom,
            goodsId: goodsId,
            dayPlannum: dayPlannum,
            note: note,
            midlist: midlist,
            cidlist: cidlist
        };
        
        console.log('最终构建的BOM数据:', bomData);
        
        return bomData;
    }
    

    
    // 手动重新生成BOM编号
    function regenerateBOMCode() {
        console.log('手动重新生成BOM编号');
        
        // 直接生成新的BOM编号，不进行唯一性检查
        const timestamp = Date.now().toString().slice(-6);
        const randomNumber = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        const newCode = `BOM${timestamp}${randomNumber}`;
        
        document.getElementById('bomCode').value = newCode;
        console.log('重新生成BOM编号成功:', newCode);
        
        if (window.layer) {
            window.layer.msg(`BOM编号已重新生成: ${newCode}`, {icon: 1});
        } else {
            alert(`BOM编号已重新生成: ${newCode}`);
        }
    }
    
    // 取消BOM编辑
    function closeBOM() {
        if (window.layer) {
            window.layer.confirm('确定要取消吗？未保存的数据将丢失。', {
                icon: 3,
                title: '确认取消'
            }, function(index) {
                window.layer.close(index);
                // 返回列表页面
                if (window.parent && window.parent.postMessage) {
                    window.parent.postMessage({ 
                        action: 'returnToList',
                        url: '/Process/BOMList',
                        title: 'BOM管理'
                    }, '*');
                } else {
                    window.location.href = '/Process/BOMList';
                }
            });
        } else {
            if (confirm('确定要取消吗？未保存的数据将丢失。')) {
                // 返回列表页面
                if (window.parent && window.parent.postMessage) {
                    window.parent.postMessage({ 
                        action: 'returnToList',
                        url: '/Process/BOMList',
                        title: 'BOM管理'
                    }, '*');
                } else {
                    window.location.href = '/Process/BOMList';
                }
            }
        }
    }
    </script>
